package cc;

import androidx.databinding.BaseObservable;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import cc.bean.NewsInfo;
import cc.common.net.HttpManager;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import okhttp3.Request;
import okhttp3.ResponseBody;

public class NewsModel extends BaseObservable {
    public Observable<List<NewsInfo>> getNews() {
        return Observable.create(new ObservableOnSubscribe<List<NewsInfo>>() {
            @Override
            public void subscribe(ObservableEmitter<List<NewsInfo>> emitter) throws Exception {
                ResponseBody body = HttpManager.getInstance().getOkHttpClient().newCall(
                        new Request.Builder().url("http://www.vojs.cn/2014new/c/k/")
                                .method("GET", null).build()
                ).execute().body();
                if (body != null) {
                    String html = body.string();
                    Document doc = Jsoup.parse(html);
                    Elements elements = doc.getElementsByClass("con-r-4");
                    List<NewsInfo> list = new ArrayList<>();
                    for (Element e : elements) {
                        NewsInfo info = new NewsInfo();
                        Node node = e.childNode(1).childNode(0);
                        info.setTitle(node.attr("alt"));
                        info.setImgs(node.attr("src"));
                        info.setLinkUrl("http://www.vojs.cn" + e.childNode(3).childNode(1).childNode(1).attr("href"));
                        list.add(info);
                    }
                    emitter.onNext(list);
                    emitter.onComplete();
                }
            }
        });
    }
}
